<?php
    /**
     * Created by PhpStorm.
     * User: jackhhy
     * Date: 2019/6/27-15:04
     * Link: https://gitee.com/luckygyl/lucky_admin
     * FileName: Menu.php
     * Keys: ctrl+alt+L/ctrl+s(代码格式化) ctrl+J(代码提示) ctrl+R(替换)ALT+INSERT(生成代码(如GET,SET方法,构造函数等) , 光标在类中才生效)
     * CTRL+ALT+O (优化导入的类和包 需要配置) SHIFT+F2(高亮错误或警告快速定位错误)
     * CTRL+SHIFT+Z(代码向前) CTRL+SHIFT+/ (块状注释) ctrl+shift+enter(智能完善代码 如if())
     */

    namespace app\admin\controller;

    use service\JsonService;
    use service\StringService;
    use service\TreeService;
    use service\UtilService;
    use think\Exception;


    class Adminmenu extends SystemBase
    {

        protected $menu;

        protected function _initialize()
        {
            parent::_initialize(); // TODO: Change the autogenerated stub
            $this->menu = new \app\admin\model\AdminMenu();//加载模型
        }



        /**
         * @return mixed|void
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: index
         * @describe: 菜单页显示
         */
        public function index()
        {
            if($this->request->isAjax()) {
                $where = [];
                $title = input("get.title") ? input("get.title") : "";
                //菜单名称
                if(!empty($title)) {
                    $where['title'] = ['like', "%$title%"];
                }
                $page  = input("get.page") ? input("get.page") : 1;
                $page  = intval($page);
                $limit = input("get.limit") ? input("get.limit") : 1;
                $limit = intval($limit);
                return GetPageData($page, $limit, $where, "admin_menu", "listorder asc", 2);
            }

            return $this->fetch();
        }



        /**
         * @return mixed
         * @author: Jackhhy
         * @name: AddMenu
         * @describe 添加菜单
         */
        public function AddMenu()
        {
            if($this->request->isAjax()) {
                $data = $this->request->post();
                try {
                    $res = $this->menu->addData($data);
                    if($res!=false) {

                        $ars = ['describe' => '添加后台菜单', 'type' => 2, 'admin_name' => self::$admin_info['username'], 'browse' => UtilService::getBrowser(), 'model' => self::$mode_name, 'controller' => self::$controller_name, 'action' => self::$action_name];
                        AddLogs($ars); //添加操作日志

                        $this->success("添加成功");
                    }
                    else {
                        $this->error("添加失败");
                    }

                } catch (Exception $exception) {
                    $this->error($exception->getMessage());
                }
            }
            $tree = TreeService::toFormatTree($this->menu->GetMenuList());//获取菜单列表
            //dump($tree);die;
            $pid = $this->request->param("id/d");//父id

            $this->assign(compact("pid", "tree"));

            return $this->fetch();
        }


        /**
         * @return mixed
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: EditMenu
         * @describe:编辑菜单
         */
        public function EditMenu()
        {
            if($this->request->isAjax()) {
                $data = $this->request->post();
                try {
                    $res = $this->menu->editData($data);
                    if($res!==false) {
                        $ars = ['describe' => '编辑后台菜单：'.$data['title'].'', 'type' => 2, 'admin_name' => self::$admin_info['username'], 'browse' => UtilService::getBrowser(), 'model' => self::$mode_name, 'controller' => self::$controller_name, 'action' => self::$action_name];
                        AddLogs($ars); //添加操作日志

                        $this->success("修改成功");
                    }
                    else {
                        $this->error("修改失败");
                    }
                } catch (Exception $exception) {
                    $this->error($exception->getMessage());
                }
            }
            $tree = TreeService::toFormatTree($this->menu->GetMenuList());//获取菜单列表
            //dump($tree);die;
            $id   = $this->request->param("id/d");//父id
            $info = $this->menu->get($id)->toArray();
            $pid  = $info['pid'];

            //dump($pid);
            $this->assign(compact("pid", "tree", "info"));

            return $this->fetch();
        }


        /**
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: delete
         * @describe:批量或者单个删除
         */
        public function delete()
        {
            if($this->request->isAjax()) {
                $ids = $this->request->post("ids");
                try {
                    $res = $this->menu->del($ids);
                    if($res) {

                        $ars = ['describe' => '删除后台菜单', 'type' => 2, 'admin_name' => self::$admin_info['username'], 'browse' => UtilService::getBrowser(), 'model' => self::$mode_name, 'controller' => self::$controller_name, 'action' => self::$action_name];
                        AddLogs($ars); //添加操作日志

                        $this->success("删除成功");
                    }
                    else {
                        $this->error("删除失败");
                    }
                } catch (Exception $exception) {
                    $this->error($exception->getMessage());
                }
            }
        }




        /**
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: Jackhhy <jackhhy520@qq.com>
         * @name: MenuListJson
         * @describe:根据权限返回菜单数据
         */
        public function MenuListJson()
        {
            if($this->request->isGet()) {
                $role_id = self::$admin_info['role_id'];
                isset($role_id) ? $role_id : 0;
                $role  = new \app\admin\model\AdminRole();//实例化角色模型
                $child = TreeService::getChildrenPid($role->GetRoleList(), $role_id); //获取该角色的子集
                if(empty($child)) {
                    //无子集
                    $res = db("admin_role")->where("id", $role_id)->value("rule"); //获取单个 权限数据
                    if(empty($res)) {
                        exit(json_encode(TreeService::DeepTree($this->menu->GetMenuList(['status' => 100])))); //未授权菜单
                    }
                    else {
                        $rule = StringService::string2array($res);
                        $all  = $this->menu->GetMenuList(["id" => ["in", $rule]]);
                        exit(json_encode(TreeService::DeepTree($all)));
                    }

                }
                else {
                    array_push($child, $role_id); //追加管理员角色id
                    $resd = db("admin_role")->where(["id" => ["in", $child], "status" => 1])->select();//获取所有
                    $node = [];
                    foreach($resd as $k => $v){
                        if(!empty($v['rule'])) {
                            $node[$k] = StringService::string2array($v['rule']);
                        }
                    }
                    if(empty($node)) {
                        exit(json_encode(TreeService::DeepTree($this->menu->GetMenuList(['status' => 100])))); //未授权菜单
                    }
                    else {
                        $str = "";
                        foreach($node as $k => $v){
                            $str .= @implode(",", $v).",";
                        }
                        $ids  = @explode(",", $str);
                        $idsf = array_unique(array_filter($ids)); //去空去重
                        $all  = $this->menu->GetMenuList(["id" => ["in", $idsf]]);
                        unset($node);
                        // dump($all);
                        exit(json_encode(TreeService::DeepTree($all)));
                    }
                }
            }

        }



    }